/*************************************************************************
	> File Name: tcp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/02 13:47
 ************************************************************************/

#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include "log.hpp"
#include <cerrno>

const int SIZE = 256;

static void service(int sock, const std::string &cli_ip, const uint16_t &cli_port)
{
    char buffer[SIZE];
    std::string messageSend = "echo# ";
    while (1) {
        memset(buffer, 0, sizeof buffer);
        ssize_t s = read(sock, buffer, sizeof buffer);
        if (s > 0) {
            std::cout << cli_ip << ":" << cli_port << "# " << buffer << std::endl;
        } else if (s == 0) {
            logMessage(NORMAL, "%s:%d shutdown.", cli_ip.c_str(), cli_port);
            break;
        } else {
            logMessage(ERROR, "read sock error, %d:%s", errno, strerror(errno));
            break;
        }
        write(sock, (messageSend + buffer).c_str(), (messageSend + buffer).size());
    }
}

class TcpServer
{
public:
    TcpServer (uint16_t port, std::string ip = "0.0.0.0"):_port(port), _ip(ip)
    {}

    bool initServer()
    {
        if ((_listenSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "Create tcp socket success, listensock:%d", _listenSock);
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if (bind(_listenSock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        if (listen(_listenSock, gbacklog) < 0) {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(3);
        }
        logMessage(NORMAL, "init tcp server success");
        return true;
    }

    void start()
    {
        while (1) {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            int servicesock = accept(_listenSock, (struct sockaddr*)&src, &len);
            if (servicesock < 0) {
                logMessage(ERROR, "%d:%s", errno, strerror(errno));
                continue;
            }
            uint16_t cli_port = ntohs(src.sin_port);
            std::string cli_ip = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "link success, servicesock:%d|%s:%d\n", servicesock, cli_ip.c_str(), cli_port);
            service(servicesock, cli_ip, cli_port);
        }
    }

private:
    const static int gbacklog = 20;
    uint16_t _port;
    std::string _ip;
    int _listenSock;
};
